//! 集成测试
//! 
//! 测试各个模块之间的协作和完整的工作流程

use dataforge::*;
use dataforge::generators::name;
use dataforge::generators::address;
use dataforge::generators::number;
use dataforge::generators::internet;
use dataforge::generators::datetime;
use serde_json::json;
use std::sync::Arc;

#[test]
fn test_basic_workflow() {
    // 创建DataForge实例
    let forge = DataForge::new(Language::ZhCN);
    
    // 测试基本生成功能
    assert!(forge.generate("uuid_v4").is_some());
    assert!(forge.generate("zh_cn_name").is_some());
}

#[test]
fn test_generator_integration() {
    // 测试各种生成器的集成使用
    let data = json!({
        "personal": {
            "name": name::zh_cn_fullname(),
            "age": number::adult_age(),
            "email": internet::email(),
            "phone": number::phone_number()
        },
        "location": {
            "province": address::zh_province(),
            "city": address::zh_city(),
            "address": address::zh_address()
        },
        "timestamps": {
            "birthday": datetime::birthday(),
            "created_at": datetime::iso8601(),
            "updated_at": datetime::timestamp()
        }
    });
    
    // 验证数据结构
    assert!(data["personal"]["name"].is_string());
    assert!(data["personal"]["age"].is_number());
    assert!(data["personal"]["email"].is_string());
    assert!(data["location"]["province"].is_string());
    assert!(data["timestamps"]["birthday"].is_string());
    
    println!("集成生成数据: {}", serde_json::to_string_pretty(&data).unwrap());
}

#[test]
fn test_batch_generation_workflow() {
    // 批量生成用户数据
    let users: Vec<serde_json::Value> = (0..10)
        .map(|i| json!({
            "id": i + 1,
            "name": name::zh_cn_fullname(),
            "age": number::adult_age(),
            "email": internet::email(),
            "phone": number::phone_number(),
            "address": address::zh_address(),
            "created_at": datetime::iso8601(),
            "active": i % 3 != 0 // 大部分用户是活跃的
        }))
        .collect();
    
    assert_eq!(users.len(), 10);
    
    // 验证每个用户的数据完整性
    for (i, user) in users.iter().enumerate() {
        assert_eq!(user["id"].as_i64().unwrap(), (i + 1) as i64);
        assert!(user["name"].is_string());
        assert!(user["age"].is_number());
        assert!(user["email"].is_string());
        assert!(user["phone"].is_string());
        assert!(user["address"].is_string());
        assert!(user["created_at"].is_string());
        assert!(user["active"].is_boolean());
        
        // 验证年龄范围
        let age = user["age"].as_i64().unwrap();
        assert!(age >= 18 && age <= 80);
        
        // 验证邮箱格式
        let email = user["email"].as_str().unwrap();
        assert!(email.contains('@'));
        assert!(email.contains('.'));
    }
    
    println!("生成了 {} 个用户", users.len());
}

#[test]
fn test_schema_parser_integration() {
    let parser = SchemaParser::new();
    
    // 定义JSON Schema
    let json_schema = json!({
        "title": "User",
        "type": "object",
        "properties": {
            "id": {
                "type": "integer",
                "description": "User ID"
            },
            "name": {
                "type": "string",
                "description": "User name"
            },
            "email": {
                "type": "string",
                "description": "User email"
            },
            "age": {
                "type": "integer",
                "minimum": 18,
                "maximum": 100
            },
            "created_at": {
                "type": "string",
                "format": "date-time"
            }
        },
        "required": ["id", "name", "email"]
    });
    
    // 解析Schema
    let result = parser.infer_from_json(&json_schema);
    assert!(result.is_ok());
    
    let schema = result.unwrap();
    assert_eq!(schema.name, "User");
    assert_eq!(schema.fields.len(), 5);
    
    // 验证字段类型推断
    let id_field = schema.fields.iter().find(|f| f.name == "id").unwrap();
    match &id_field.data_type {
        DataType::Integer { .. } => {},
        _ => panic!("Expected Integer type for id field"),
    }
    
    let email_field = schema.fields.iter().find(|f| f.name == "email").unwrap();
    match &email_field.data_type {
        DataType::Email => {},
        _ => panic!("Expected Email type for email field"),
    }
    
    println!("解析的Schema: {:?}", schema);
}

#[test]
fn test_database_forge_integration() {
    let forge = SimpleDatabaseForge::new("sqlite://test.db")
        .batch_size(100);
    
    let config = forge.table("users", 5, |t| {
        t.field("id", || json!(uuid_v4()))
         .field("name", || json!(name::zh_cn_fullname()))
         .field("age", || json!(number::adult_age()))
         .field("email", || json!(internet::email()))
         .field("created_at", || json!(datetime::iso8601()))
    });
    
    // 执行同步填充
    let result = config.fill_sync();
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), 5);
}

#[test]
fn test_memory_pool_integration() {
    let config = MemoryPoolConfig {
        initial_size: 1000,
        max_size: 10000,
        size_classes: vec![64, 128, 256, 512, 1024],
        cleanup_interval: std::time::Duration::from_secs(300),
        max_idle_time: std::time::Duration::from_secs(600),
    };
    
    let pool = MemoryPool::new(config);
    
    // 测试内存池与生成器的集成
    // 分配大量不同大小的缓冲区，确保超过预分配的数量
    for i in 0..2000 {
        let name = name::zh_cn_fullname();
        let size = if i % 10 == 0 { 2048 } else { name.len() }; // 有些分配使用大尺寸
        let _buffer = pool.allocate(size);
        // 模拟使用内存池存储生成的数据
    }
    
    let stats = pool.stats();
    assert!(stats.total_allocations > 0);
    // 由于内存池预分配了缓冲区，大部分分配可能是缓存命中
    // 我们主要验证分配计数和活跃缓冲区数量
    assert!(stats.active_buffers > 0);
    
    println!("内存池统计: {:?}", stats);
}

#[test]
fn test_rule_engine_integration() {
    let string_pool = Arc::new(StringPool::new(1000));
    let mut engine = RuleEngine::new(string_pool);
    
    // 添加数据验证规则
    let email_rule = Rule {
        id: "email_validation".to_string(),
        name: "Email Validation".to_string(),
        rule_type: RuleType::Regex { 
            pattern: r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$".to_string(),
            flags: None 
        },
        priority: 100,
        enabled: true,
        description: Some("Email format validation".to_string()),
        tags: vec!["validation".to_string()],
        parent_id: None,
    };
    
    engine.add_rule(email_rule);
    
    // 创建规则上下文
    let context = RuleContext {
        field_name: "email".to_string(),
        current_value: Some(json!(internet::email())),
        params: std::collections::HashMap::new(),
        generation_history: Vec::new(),
    };
    
    // 执行规则
    let result = engine.execute_rule("email_validation", &context);
    assert!(result.is_ok());
    
    println!("规则执行结果: {:?}", result);
}

#[test]
fn test_config_management_integration() {
    // 创建配置
    let mut config = Config::default();
    config.data_generation.batch_size = 500;
    config.data_generation.null_probability = 0.1;
    
    // 添加数据库配置
    let db_config = DatabaseConfig {
        url: "sqlite://integration_test.db".to_string(),
        max_connections: 10,
        batch_insert_size: 1000,
        ..Default::default()
    };
    config.databases.insert("test_db".to_string(), db_config);
    
    // 创建配置管理器
    let manager = ConfigManager::new(config);
    
    // 验证配置
    assert!(manager.validate().is_ok());
    assert_eq!(manager.config().data_generation.batch_size, 500);
    
    let db_config = manager.get_database_config("test_db");
    assert!(db_config.is_some());
    assert_eq!(db_config.unwrap().url, "sqlite://integration_test.db");
}

#[test]
fn test_parallel_generation_integration() {
    use rayon::prelude::*;
    
    // 并行生成大量数据
    let data: Vec<serde_json::Value> = (0..100)
        .into_par_iter()
        .map(|i| json!({
            "id": i,
            "name": name::zh_cn_fullname(),
            "email": internet::email(),
            "score": number::score(),
            "created_at": datetime::iso8601()
        }))
        .collect();
    
    assert_eq!(data.len(), 100);
    
    // 验证并行生成的数据质量
    for item in data.iter().take(10) {
        assert!(item["name"].is_string());
        assert!(item["email"].is_string());
        assert!(item["score"].is_number());
        assert!(item["created_at"].is_string());
        
        let score = item["score"].as_i64().unwrap();
        assert!(score >= 0 && score <= 100);
    }
    
    println!("并行生成了 {} 条记录", data.len());
}

#[test]
fn test_error_handling_integration() {
    // 测试各种错误情况的处理
    
    // 1. Schema解析错误
    let parser = SchemaParser::new();
    let invalid_schema = json!("invalid");
    let result = parser.infer_from_json(&invalid_schema);
    assert!(result.is_err());
    
    // 2. 数据库连接错误（模拟）
    let forge = SimpleDatabaseForge::new("invalid://connection");
    // 这里只测试配置创建，不测试实际连接
    assert_eq!(forge.connection_string(), "invalid://connection");
    
    // 3. 配置验证错误
    let mut config = Config::default();
    config.data_generation.batch_size = 0; // 无效的批次大小
    let manager = ConfigManager::new(config);
    // 注意：这里假设validate方法会检查batch_size > 0
    // 实际实现中需要添加这种验证逻辑
}

#[test]
fn test_complete_workflow() {
    // 完整的数据生成工作流程测试
    
    // 1. 创建配置
    let mut config = Config::default();
    config.data_generation.batch_size = 50;
    
    // 2. 创建Schema
    let parser = SchemaParser::new();
    let json_schema = json!({
        "title": "Product",
        "properties": {
            "id": {"type": "integer"},
            "name": {"type": "string"},
            "price": {"type": "number"},
            "created_at": {"type": "string", "format": "date-time"}
        }
    });
    
    let schema = parser.infer_from_json(&json_schema).unwrap();
    assert_eq!(schema.name, "Product");
    
    // 3. 生成数据
    let products: Vec<serde_json::Value> = (0..config.data_generation.batch_size)
        .map(|i| json!({
            "id": i + 1,
            "name": format!("产品{}", name::zh_cn_fullname()),
            "price": number::price(),
            "created_at": datetime::iso8601()
        }))
        .collect();
    
    assert_eq!(products.len(), 50);
    
    // 4. 验证生成的数据
    for product in products.iter().take(5) {
        assert!(product["id"].is_number());
        assert!(product["name"].is_string());
        assert!(product["price"].is_number());
        assert!(product["created_at"].is_string());
        
        let price = product["price"].as_f64().unwrap();
        assert!(price >= 0.0);
    }
    
    println!("完整工作流程测试完成，生成了 {} 个产品", products.len());
}